<template>
  <div>
    <!-- 按钮 -->
    <el-button style="margin:10px" type="primary" icon="el-icon-refresh-right" circle
      @click="getMembersList"></el-button>
    <el-button type="primary" icon="el-icon-plus" style="margin:10px" @click="getShow"
      v-if="Register != -1">添加后台人员</el-button>
    <el-input placeholder="请输入搜索内容在点击搜索" v-model="searchText" style="width:300px;background-color: #fff;">
      <el-tooltip content="搜索用户" placement="top" slot="append">
        <el-button icon="el-icon-search" @click="getMembersList"></el-button>
      </el-tooltip>
    </el-input>
    <el-button style="margin:10px" @click="reSetting">重置</el-button>
    <el-button style="margin:10px" @click="clickExport" :loading="buttonLoading">用户一键导入TIM</el-button>
    <!-- 表格
      data 展示数据 —— 数组类型
    -->
    <el-table style="width: 100%;" border :data="list">
      <el-table-column prop="nickName" label="昵称" align="center">
      </el-table-column>
      <!--      <el-table-column prop="userName" label="用户名" align="center">
      </el-table-column> -->
      <el-table-column prop="sex" label="性别" align="center" width="60">
        <template slot-scope="{ row, $index }">
          <!-- <p>{{ row.sex == 1 ? '男' : '女' }}</p> -->
          <p v-if="row.sex == 1">男</p>
          <p v-if="row.sex == 2">女</p>
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" width="80">
        <template slot-scope="{ row, $index }">
          <el-image v-if="row.headimgurl" :src="$staticURL + row.headimgurl" style=" width:40px; height:40px"
            :preview-src-list="[$staticURL + row.headimgurl]" />
        </template>
      </el-table-column>
      <el-table-column prop="goldCoin" label="金币" align="center">
      </el-table-column>
      <el-table-column prop="balance" label="零钱" align="center">
      </el-table-column>
      <el-table-column prop="advertisementMoney" label="广告金" align="center">
      </el-table-column>
      <el-table-column prop="province" label="地址" align="center">
      </el-table-column>
      <el-table-column prop="name" label="真实姓名" align="center">
      </el-table-column>
      <el-table-column prop="idcard" label="身份证号" align="center">
      </el-table-column>
      <el-table-column prop="phone" label="电话号码" align="center">
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center">
      </el-table-column>
      <!-- <el-table-column prop="userRole" label="角色身份" align="center">
      </el-table-column> -->
      <!-- <el-table-column prop="userRole" label="角色" align="center">
      </el-table-column> -->
      <!-- <el-table-column label="操作" align="center">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" icon="el-icon-edit" circle></el-button>
          <el-popconfirm title="是否删除该用户？" icon="el-icon-info" icon-color="red" @confirm="getDelete(row.id)">
            <el-tooltip content="删除用户" placement="top" slot="reference">
              <el-button type="danger" icon="el-icon-delete"></el-button>
            </el-tooltip>
          </el-popconfirm>
        </template>
      </el-table-column> -->
    </el-table>

    <!-- 分页 -->
    <el-pagination style="margin-top:20px;textAlign:center" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" :current-page="pageNumber" :page-sizes="[10, 50, 100]" :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <!-- 对话框  -->
    <el-dialog title="添加后台人员" :visible.sync="dialogFormVisible">
      <el-form style="width:80%" :model="tmForm" :rules="rules" ref="ruleForm">
        <el-form-item v-show="tmForm.roleId != 9" label="昵称" label-width="150px" prop="nickName">
          <el-input autocomplete="off" v-model="tmForm.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户名" label-width="150px" prop="userName">
          <el-input autocomplete="off" v-model="tmForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="150px" prop="password">
          <el-input autocomplete="off" type="password" v-model="tmForm.password"></el-input>
        </el-form-item>
        <el-form-item v-show="tmForm.roleId != 9" label="性别" label-width="150px" prop="sex">
          <el-radio v-model="tmForm.sex" label="1">男</el-radio>
          <el-radio v-model="tmForm.sex" label="2">女</el-radio>
        </el-form-item>
        <el-form-item label="角色权限" label-width="150px" prop="roleId">
          <el-select v-model="tmForm.roleId" placeholder="请选择">
            <el-option v-for="item in options" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <div v-show="tmForm.roleId == 9">
          <el-form-item label="当月充值金额指标" label-width="150px" required>
            <el-input autocomplete="off" v-model="monthRechargeMoney"></el-input>
          </el-form-item>
          <el-form-item label="奖励金额" label-width="150px" required>
            <el-input autocomplete="off" v-model="rewardMoney"></el-input>
          </el-form-item>
          <el-form-item label="广告折扣" label-width="150px" required>
            <el-input autocomplete="off" v-model="rate" placeholder="小数点格式，不大于1"></el-input>
          </el-form-item>
          <el-form-item label="用户消费返比例" label-width="150px" required>
            <el-input autocomplete="off" v-model="distributionRate" placeholder="小数点格式，不大于1"></el-input>
          </el-form-item>
          <el-form-item label="应交押金金额" label-width="150px" required>
            <el-input autocomplete="off" v-model="payableDepositMoney"></el-input>
          </el-form-item>
        </div>
        <!-- 上传图片 -->
        <el-form-item v-show="tmForm.roleId != 9" label="上传头像" label-width="150px" prop="headimgurl">
          <el-upload class="avatar-uploader" action="https://api.yushiai.com.cn/biz/uploadImgage" :headers="headers"
            name="image" :show-file-list="false" :on-success="handleAvatarSuccess">
            <img v-if="tmForm.headimgurl" :src="'https://www.yushiai.com.cn/' + tmForm.headimgurl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/gif/webp文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="getRegister">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getToken
} from '@/utils/auth';
import axios from 'axios'
import { genTestUserSig } from '@/debug'
import request from '@/utils/request'

export default {
  name: 'Members',
  //挂载完毕发送请求
  mounted() {
    //获取列表数据方法
    this.getMembersList()
    this.getRoleList();
  },
  data() {
    return {
      monthRechargeMoney: '',
      rate: '',
      rewardMoney: '',
      payableDepositMoney: '',
      distributionRate: '',

      //页码
      pageNumber: 1,
      //每页数量
      pageSize: 10,
      //总条数
      total: 0,
      //列表数据
      list: [],
      //角色数组
      options: [],
      dialogFormVisible: false,
      tmForm: {
        nickName: '',
        userName: '',
        password: '',
        headimgurl: '',
        roleId: '',
        sex: ''
      },
      //搜索
      searchText: '',
      // 表单验证
      rules: {
        nickName: [{
          required: true,
          message: '请输入昵称',
          trigger: 'blur'
        },
        {
          min: 2,
          message: '长度在 2 个字符以上',
          trigger: 'change'
        }
        ],
        userName: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }],
        sex: [{
          required: true,
          message: '请输入性别',
          trigger: 'blur'
        }],
        headimgurl: [{
          required: true,
          message: '请上传头像'
        }],
        roleId: [{
          required: true,
          message: '请选择角色',
          trigger: 'blur'
        }]
      },
      params: {
        pageNumber: 1,
        pageSize: 100
      },
      buttonLoading: false
    }
  },
  computed: {
    headers() {
      return {
        'session_token': getToken()
      };
    },
    Register() {
      return this.$store.state.user.treesId.indexOf('Register')
    }
  },
  methods: {
    clickExport() {
      this.buttonLoading = true
      this.exportUsr()
    },
    exportUsr() {
      const imgUrl = 'https://www.yushiai.com.cn/'
      const { userSig } = genTestUserSig({ secretKey: '0e76e29430d2719c12c5a1261c9f157343b795991a3aac885f392063f85106b3', userID: '2345', SDKAppID: 1600064516 })
      const identifier = 2345
      const sdkappid = 1600064516
      const random = Math.floor(Math.random() * 4294967295) // 生成0-4294967294之间的随机数
      console.log('@', userSig)

      request({
        url: '/biz/getAllUserMessage',
        method: 'post',
        data: this.params
      }).then(res => {
        const sumPage = res.data.sumPage
        let rows = res.data.rows
        let AccountList = []
        rows.forEach(item => {
          item.headimgurl = `${imgUrl}${item.headimgurl}`
          AccountList.push({
            UserID: `${item.id}`,
            Nick: `${item.nickName}`,
            FaceUrl: item.headimgurl
          })
        })
        AccountList = AccountList.filter(item => {
          return item.UserID != 222
        })
        axios.post(`https://console.tim.qq.com/v4/im_open_login_svc/multiaccount_import?sdkappid=${sdkappid}&identifier=${identifier}&usersig=${userSig}&random=${random}&contenttype=json`, {
          AccountList: AccountList
        }).then(res => {
          if (res.data.ActionStatus == 'OK') {
            this.params.pageNumber++
            if (this.params.pageNumber <= sumPage) {
              requestIdleCallback(() => {
                this.exportUsr()
              })
            } else {
              this.buttonLoading = false
              this.$message({
                type: 'success',
                message: '用户一键导入TIM成功'
              })
            }
          } else {
            this.buttonLoading = false
          }
        })
      })
    },
    async getRoleList() {
      let res = await this.$API.permissions.getRoleList();
      this.options = res.data;
    },
    async getMembersList() {
      let res = await this.$API.members.getAllUserMessage({
        pageNumber: this.pageNumber,
        pageSize: this.pageSize,
        searchText: this.searchText
      })
      this.searchText = '';
      this.total = res.data.sumLine;
      this.list = res.data.rows;
    },
    reSetting() {
      this.searchText = '';
      this.getMembersList();
    },
    async getDelete(id) {
      let res = await this.$API.members.getDeleteUser({
        userId: id
      })
      this.getMembersList();
    },
    // 点击添加
    getShow() {
      this.dialogFormVisible = true
      this.tmForm = {
        nickName: '',
        userName: '',
        password: '',
        headimgurl: '',
        roleId: '',
        sex: ''
      }
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      console.log(res, file)
      this.tmForm.headimgurl = res.data.imgageUrl;
    },
    // 添加管理员
    getRegister() {
      // console.log('添加人员', this.tmForm, this.rate, this.rewardMoney, this.monthRechargeMoney)
      // return;
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.tmForm.roleId == 9) {
            if (this.monthRechargeMoney == '' || this.rate == '' || this.rewardMoney == '' || this
              .distributionRate == '' || this.payableDepositMoney == '') {
              this.$message.info("请填写相关信息");
              return;
            }
            let res1 = await this.$API.members.addAdvertisementUser({
              monthRechargeMoney: this.monthRechargeMoney,
              userName: this.tmForm.userName,
              password: this.tmForm.password,
              rate: this.rate,
              rewardMoney: this.rewardMoney,
              payableDepositMoney: this.payableDepositMoney,
              distributionRate: this.distributionRate
            });
            console.log('广告商注册', res1)
            if (res1.code == 200) {
              this.$message.success('广告商注册成功')
            } else {
              this.$message(res1.msg)
            }
          } else {
            let res = await this.$API.members.getRegister(this.tmForm);
            if (res.code == 200) {
              this.$message.success('添加后台用户成功')
            } else {
              this.$message(res.msg)
            }
          }
          this.dialogFormVisible = false;
          this.getMembersList()
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getMembersList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.pageNumber = val;
      this.getMembersList();
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
